package sqs

import (
	"os"
	"http"
	"goaws.googlecode.com/hg/aws"
)

const (
	REGION_US_EAST_1_ENDPOINT      string = "sqs.us-east-1.amazonaws.com"      // Northern Virginia
	REGION_US_WEST_1_ENDPOINT      string = "sqs.us-west-1.amazonaws.com"      // Northern California
	REGION_EU_WEST_1_ENDPOINT      string = "sqs.eu-west-1.amazonaws.com"      // Ireland
	REGION_AP_SOUTHEAST_1_ENDPOINT string = "sqs.ap-southeast-1.amazonaws.com" // Singapore
	REGION_AP_NORTHEAST_1_ENDPOINT string = "sqs.ap-northeast-1.amazonaws.com" // Tokyo
	DEFAULT_ENDPOINT               = REGION_US_EAST_1_ENDPOINT
)

var RegionEndpoints = map[string]string{
	aws.REGION_US_EAST_1:      REGION_US_EAST_1_ENDPOINT,
	aws.REGION_US_WEST_1:      REGION_US_WEST_1_ENDPOINT,
	aws.REGION_EU_WEST_1:      REGION_EU_WEST_1_ENDPOINT,
	aws.REGION_AP_SOUTHEAST_1: REGION_AP_SOUTHEAST_1_ENDPOINT,
	aws.REGION_AP_NORTHEAST_1: REGION_AP_NORTHEAST_1_ENDPOINT,
}

const (
	DEFAULT_VISIBILITY_TIMEOUT int = 30
)

type Conn struct {
	URL string
	rpc *aws.QueryRPC
}

func Connect(keys aws.AccessKeys, endpoint string, secure bool) *Conn {
	if endpoint == "" {
		endpoint = DEFAULT_ENDPOINT
	}
	return &Conn{aws.EndpointURL(endpoint, secure), &aws.QueryRPC{keys, "2009-02-01", "2"}}
}

func (c *Conn) getResponse(action string, path string, params map[string]string, xmlResp interface{}) (err os.Error) {
	return c.rpc.UnmarshalXMLResponse(c.URL+path, action, params, xmlResp, newErrorResponse)
}

func OpenQueue(keys aws.AccessKeys, queueURL string) (queue *Queue, err os.Error) {
	url, err := http.ParseURL(queueURL)
	if err != nil {
		return
	}

	return &Queue{Connect(keys, url.Host, url.Scheme == "https"), url.Path}, nil
}
